package com.xuequ.answerme.manager;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.xuequ.answerme.beans.AnswerBean;
import com.xuequ.answerme.beans.QuestionBean;
import com.xuequ.answerme.beans.UserBean;
import com.xuequ.answerme.tools.Tools;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by Shijie on 2015/10/2.
 */
public class UserManager {

    public interface CheckIsValidListener{
        void checkIsValidOnSuccess(Integer isValid);
        void checkIsValidOnFailure(String isValid);
    }

    public interface AddNewUserListener {
        void addNewUserOnSuccess();

        void addNewUserOnFailure(String failureMsg);
    }

    public interface LoginListener {
        void loginOnSuccess(UserBean userBean);

        void loginOnFailure(String failureMsg);
    }

    public interface FindPhoneNumberIsValidListener {
        void findPhoneNumberIsValidOnSuccess(Integer isValid);

        void findPhoneNumberIsValidOnFailure(String failureMsg);
    }

    public interface UpdateUserInfoListener{
        void updateUserInfoOnSuccess();
        void updateUserInfoOnFailure(String failureMsg);
    }

    public interface FindFocusListener {
        void findFocusOnSuccess(List<QuestionBean> questionBeans, int count);

        void findFocusOnFailure(String failureMsg);
    }

    public interface FocusOrNotListener {
        void focusOrNotOnSuccess();

        void focusOrNotOnFailure(String failureMsg);

    }

    public interface FindLikeListener {
        void findLikeOnSuccess(List<AnswerBean> answerBeans, int count);

        void findLikeOnFailure(String failureMsg);
    }

    public interface LikeOrNotListener {
        void likeOrNotOnSuccess();

        void likeOrNotOnFailure(String failureMsg);

    }

    public interface FindAllMyQuestionsListener{
        void findAllMyQuestionsOnSuccess(List<QuestionBean> questions, int count);
        void findAllMyQuestionsOnFailure(String failureMsg);
    }

    public interface CheckIsLikeOrFocusListener{
        void checkIsLikeOrFocusOnSuccess(List<AnswerBean> answerBeans);
        void checkIsLikeOrFocusOnFailure(String failureMsg);
    }

    /**
     * 手机号码
     * （手机必须是验证过的）
     *
     * @param context       上下文
     * @param account       手机号码
     * @param password      密码
     * @param loginListener 登陆listener
     */
    public void LoginByPhoneNumber(final Context context, final String account, String password, final LoginListener loginListener) {

        BmobUser.loginByAccount(context, account, password, new LogInListener<UserBean>() {
            @Override
            public void done(UserBean userBean, BmobException e) {
                if (e == null) {
                    loginListener.loginOnSuccess(userBean);
                } else {
                    if (e.toString().contains("username or password incorrect")) {
                        new UserManager().FindPhoneNumberIsValid(context, account, new FindPhoneNumberIsValidListener() {
                            @Override
                            public void findPhoneNumberIsValidOnSuccess(Integer isValid) {
                                if (isValid != 0) {
                                    loginListener.loginOnFailure("密码错误");
                                } else {
                                    loginListener.loginOnFailure("手机号码错误");
                                }
                            }

                            @Override
                            public void findPhoneNumberIsValidOnFailure(String failureMsg) {
                            }
                        });

                    } else {
                        loginListener.loginOnFailure(e.toString());
                    }

                }
            }
        });
    }

    /**
     * 注册新用户
     * （手机号码，邮箱，用户名都要唯一）
     *
     * @param context            上下文
     * @param userBean           用户类
     * @param addNewUserListener 注册新用户listener
     */
    public void AddNewUser(Context context, UserBean userBean, final AddNewUserListener addNewUserListener) {

        userBean.signUp(context, new SaveListener() {
            @Override
            public void onSuccess() {
                addNewUserListener.addNewUserOnSuccess();
            }

            @Override
            public void onFailure(int i, String s) {
                addNewUserListener.addNewUserOnFailure(s);
            }
        });
    }

    /**
     * 查找是否有号码存在
     *
     * @param context                        上下文
     * @param phoneNumber                    手机号码
     * @param findPhoneNumberIsValidListener 查找手机号码listener
     */
    public void FindPhoneNumberIsValid(Context context, String phoneNumber, final FindPhoneNumberIsValidListener findPhoneNumberIsValidListener) {

        BmobQuery<UserBean> userBeans = new BmobQuery<>();
        userBeans.addWhereEqualTo("mobilePhoneNumber", phoneNumber);
        userBeans.count(context, UserBean.class, new CountListener() {
            @Override
            public void onSuccess(int i) {
                findPhoneNumberIsValidListener.findPhoneNumberIsValidOnSuccess(i);
            }

            @Override
            public void onFailure(int i, String s) {
                findPhoneNumberIsValidListener.findPhoneNumberIsValidOnFailure(s);
            }
        });

    }

    /**
     * 寻找用户关注的所有问题
     *
     * @param context           上下文
     * @param userBean          用户
     * @param findFocusListener 监听器
     */
    public void findFocus(Context context, UserBean userBean, final FindFocusListener findFocusListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();
            questionBeans.addWhereRelatedTo("focus", new BmobPointer(userBean));
            questionBeans.include("questioner");
            questionBeans.setLimit(20);
            questionBeans.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    findFocusListener.findFocusOnSuccess(list, list.size());
                }

                @Override
                public void onError(int i, String s) {
                    findFocusListener.findFocusOnFailure(s);
                }
            });

        } else {
            findFocusListener.findFocusOnFailure("网络不可用");
        }
    }

    public void allFocusCount(Context context, UserBean userBean, final FindFocusListener findFocusListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();
            questionBeans.addWhereRelatedTo("focus", new BmobPointer(userBean));
            questionBeans.include("questioner");
            questionBeans.count(context, QuestionBean.class, new CountListener() {
                @Override
                public void onSuccess(int i) {
                    findFocusListener.findFocusOnSuccess(null, i);
                }

                @Override
                public void onFailure(int i, String s) {
                    findFocusListener.findFocusOnFailure(s);
                }
            });

        } else {
            findFocusListener.findFocusOnFailure("网络不可用");
        }
    }

    /**
     * 关注或取关某问题
     *
     * @param context            上下文
     * @param questionBean       要关注或取关的问题
     * @param userBean           用户
     * @param isFocus            之前的关注状态
     * @param focusOrNotListener 监听器
     */
    public void focusOrNot(Context context, QuestionBean questionBean, UserBean userBean, boolean isFocus, final FocusOrNotListener focusOrNotListener) {
        if (Tools.isNetAvailable(context)) {
            UserBean user = new UserBean();
            user.setObjectId(userBean.getObjectId());
            BmobRelation relation = new BmobRelation();
            if (isFocus) {
                //如果之前就关注了的，就取消关注
                relation.remove(questionBean);
            } else {
                //如果之前没有关注的，就关注
                relation.add(questionBean);
            }
            user.setFocus(relation);
            user.update(context, new UpdateListener() {
                @Override
                public void onSuccess() {
                    focusOrNotListener.focusOrNotOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    focusOrNotListener.focusOrNotOnFailure(s);
                }
            });
        } else {
            focusOrNotListener.focusOrNotOnFailure("网络不可用");
        }
    }

    /**
     * 喜欢或不喜欢某个答案
     *
     * @param context           上下文
     * @param answerBean        喜欢或不喜欢的问题
     * @param userBean          用户
     * @param isLike           之前是否被喜欢
     * @param likeOrNotListener 监听器
     */
    public void likeOrNot(Context context, AnswerBean answerBean, UserBean userBean, boolean isLike, final LikeOrNotListener likeOrNotListener) {
        if (Tools.isNetAvailable(context)) {
            UserBean user = new UserBean();
            user.setObjectId(userBean.getObjectId());
            BmobRelation relation = new BmobRelation();
            if (isLike) {
                //如果之前就关注了的，就取消关注
                relation.remove(answerBean);
            } else {
                //如果之前没有关注的，就关注
                relation.add(answerBean);
            }
            user.setLike(relation);
            user.update(context, new UpdateListener() {
                @Override
                public void onSuccess() {
                    likeOrNotListener.likeOrNotOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    likeOrNotListener.likeOrNotOnFailure(s);
                }
            });
        } else {
            likeOrNotListener.likeOrNotOnFailure("网络不可用");
        }
    }

    /**
     * 寻找用户关注的所有答案
     *
     * @param context          上下文
     * @param userBean         用户
     * @param findLikeListener 监听器
     */
    public void findLikes(Context context, UserBean userBean, final FindLikeListener findLikeListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<AnswerBean> answerBeans = new BmobQuery<>();
            answerBeans.addWhereRelatedTo("like", new BmobPointer(userBean));
            answerBeans.include("answerer");
            answerBeans.setLimit(20);
            answerBeans.findObjects(context, new FindListener<AnswerBean>() {
                @Override
                public void onSuccess(List<AnswerBean> list) {
                    findLikeListener.findLikeOnSuccess(list, list.size());
                }

                @Override
                public void onError(int i, String s) {
                    findLikeListener.findLikeOnFailure(s);
                }
            });

        } else {
            findLikeListener.findLikeOnFailure("网络不可用");
        }
    }

    public void allLikeCount(Context context, UserBean userBean, final FindLikeListener findLikeListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<AnswerBean> answerBeans = new BmobQuery<>();
            answerBeans.addWhereRelatedTo("like", new BmobPointer(userBean));
            answerBeans.include("answerer");
            answerBeans.count(context, AnswerBean.class, new CountListener() {
                @Override
                public void onSuccess(int i) {
                    findLikeListener.findLikeOnSuccess(null, i);
                }

                @Override
                public void onFailure(int i, String s) {
                    findLikeListener.findLikeOnFailure(s);
                }
            });

        } else {
            findLikeListener.findLikeOnFailure("网络不可用");
        }
    }


    /**
     *
     * @param context
     * @param userBean
     * @param findAllMyQuestionsListener
     */
    public void findAllMyQuestions(Context context, UserBean userBean, final FindAllMyQuestionsListener findAllMyQuestionsListener){
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questions = new BmobQuery<>();
            questions.addWhereEqualTo("questioner", new BmobPointer(userBean));
            questions.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    findAllMyQuestionsListener.findAllMyQuestionsOnSuccess(list, list.size());
                }

                @Override
                public void onError(int i, String s) {
                    findAllMyQuestionsListener.findAllMyQuestionsOnFailure(s);
                }
            });
        }else {
            findAllMyQuestionsListener.findAllMyQuestionsOnFailure("网络不可用");
        }

    }

    public void allMyQuestionsCount(Context context, UserBean userBean, final FindAllMyQuestionsListener findAllMyQuestionsListener){
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questions = new BmobQuery<>();
            questions.addWhereEqualTo("questioner", new BmobPointer(userBean));
            questions.count(context, QuestionBean.class, new CountListener() {
                @Override
                public void onSuccess(int i) {
                    findAllMyQuestionsListener.findAllMyQuestionsOnSuccess(null, i);
                }

                @Override
                public void onFailure(int i, String s) {
                    findAllMyQuestionsListener.findAllMyQuestionsOnFailure(s);
                }
            });
        }else {
            findAllMyQuestionsListener.findAllMyQuestionsOnFailure("网络不可用");
        }

    }

    public void checkIsFocus(Context context, UserBean userBean, final FindFocusListener findFocusListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();
            questionBeans.addWhereRelatedTo("focus", new BmobPointer(userBean));
            questionBeans.addWhereEqualTo("questioner", userBean);
            questionBeans.include("questioner");
            questionBeans.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    findFocusListener.findFocusOnSuccess(list, list.size());
                }

                @Override
                public void onError(int i, String s) {
                    findFocusListener.findFocusOnFailure(s);
                }
            });
        } else {
            findFocusListener.findFocusOnFailure("网络不可用");
        }
    }


    public void checkIsLike(Context context, UserBean userBean, final CheckIsLikeOrFocusListener checkIsLikeOrFocusListener){
        if(Tools.isNetAvailable(context)){

            BmobQuery<AnswerBean> answerBeans = new BmobQuery<>();
            answerBeans.addWhereRelatedTo("like", new BmobPointer(userBean));
            answerBeans.addWhereEqualTo("answerer", userBean);
            answerBeans.include("answerer");
            answerBeans.findObjects(context, new FindListener<AnswerBean>() {
                @Override
                public void onSuccess(List<AnswerBean> list) {
                    checkIsLikeOrFocusListener.checkIsLikeOrFocusOnSuccess(list);
                }

                @Override
                public void onError(int i, String s) {
                    checkIsLikeOrFocusListener.checkIsLikeOrFocusOnFailure(s);
                }
            });
        }else {
            checkIsLikeOrFocusListener.checkIsLikeOrFocusOnFailure("网络不可用");
        }
    }

    /**
     * 检查新用户名是否可用
     *
     * @param context
     * @param newUsername
     * @param checkIsValidListener
     */
    public void checkUsernameIsValid(Context context, String newUsername, final CheckIsValidListener checkIsValidListener){
        if(Tools.isNetAvailable(context)){
            BmobQuery<UserBean> userBeans = new BmobQuery<>();
            userBeans.addWhereEqualTo("username", newUsername);
            userBeans.count(context, UserBean.class, new CountListener() {
                @Override
                public void onSuccess(int i) {
                    checkIsValidListener.checkIsValidOnSuccess(i);
                }

                @Override
                public void onFailure(int i, String s) {
                    checkIsValidListener.checkIsValidOnFailure(s);
                }
            });
        }else {
            checkIsValidListener.checkIsValidOnFailure("网络不可用");
        }


    }

    public void updateUsername(Context context, String newUsername, final UpdateUserInfoListener updateUserInfoListener){
        if(Tools.isNetAvailable(context)){
            BmobUser newUser = new BmobUser();
            newUser.setUsername(newUsername);
            BmobUser bmobUser = BmobUser.getCurrentUser(context);
            newUser.update(context, bmobUser.getObjectId(), new UpdateListener() {
                @Override
                public void onSuccess() {
                    updateUserInfoListener.updateUserInfoOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    updateUserInfoListener.updateUserInfoOnFailure(s);
                }
            });
        }else {
            updateUserInfoListener.updateUserInfoOnFailure("网络不可用");
        }
    }

    public void updateSignature(Context context, String newSignature, final UpdateUserInfoListener updateUserInfoListener){
        if(Tools.isNetAvailable(context)){
            UserBean newUser = new UserBean();
            newUser.setSignature(newSignature);
            newUser.update(context, BmobUser.getCurrentUser(context, UserBean.class).getObjectId(), new UpdateListener() {
                @Override
                public void onSuccess() {
                    updateUserInfoListener.updateUserInfoOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    updateUserInfoListener.updateUserInfoOnFailure(s);
                }
            });
        }else {
            updateUserInfoListener.updateUserInfoOnFailure("网络不可用");
        }
    }

    /**
     * 更新用户头像
     *
     * @param context 上下文
     * @param updateUserInfoListener listener
     */
    public void updateAvatar(final Context context, final UpdateUserInfoListener updateUserInfoListener){
        if(Tools.isNetAvailable(context)){
            final BmobFile bmobFile = new BmobFile(new File(Environment.getExternalStorageDirectory()+"/avatar.png"));
            bmobFile.upload(context, new UploadFileListener() {
                @Override
                public void onSuccess() {
                    UserBean userBean = new UserBean();
                    userBean.setAvatar(bmobFile);
                    userBean.update(context, BmobUser.getCurrentUser(context, UserBean.class).getObjectId(), new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            Log.i("avatar", "--------------------------------->success" + bmobFile.getFileUrl(context));
                            updateUserInfoListener.updateUserInfoOnSuccess();
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            updateUserInfoListener.updateUserInfoOnFailure("s");
                            Log.i("avatar", "--------------------------------->failure update "+s);
                        }
                    });
                }

                @Override
                public void onFailure(int i, String s) {
                    updateUserInfoListener.updateUserInfoOnFailure(s);
                }
            });


        }else {
            updateUserInfoListener.updateUserInfoOnFailure("网络不可用");
        }
    }

}
